from turbogears import controllers, expose, identity, widgets, validators, error_handler, validate, paginate
import routes

from gibe.plugin import add_plugin_data, plugins
from gibe.util import utcnow, utc 
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
from gibe import model
from gibethemetechgeneral2008a.model import ChannelEntry, EntryTag, Entry

import itertools

def add_utc_timezone(d):
    return d.replace(tzinfo=utc)

def classify(service_url, suffix = ""):
    replaced = suffix + service_url.replace("/", "_").replace(".", "_").replace(':', "_")
    while '__' in replaced:
        replaced = replaced.replace('__', '_')
    while replaced[-1:] == '_':
        replaced = replaced[:-1]
    while replaced[0] == '_':
        replaced = replaced[1:]
    return replaced

def class_enumerate(iterable):
    for i, v in enumerate(iterable):
        classes = []
        if i == 0:
            classes.append("first")
        if i % 2 == 0:
            classes.append("even")
        if i % 2 == 1:
            classes.append("odd")
        yield i, " ".join(classes), v


class TechGeneralController(controllers.Controller):
    @expose(template="genshi:gibethemetechgeneral2008a.templates.frontpage")
    @add_plugin_data(template="genshi:gibethemetechgeneral2008a.templates.frontpage")
    def frontpage(self, blog, action):
        limit = 10
        entries = model.session.query(ChannelEntry).filter(ChannelEntry.c.selected == True).order_by(model.desc(ChannelEntry.c.published)).limit(limit)

        entries = list(entries)

        def day_func(e):
            return date(e.published.year, e.published.month, e.published.day)

        now = utcnow()

        def display_day(some_date):
            if some_date == now.date():
                return "Today"

            if some_date == now.date() - timedelta(days=1):
                return "Yesterday"

            return some_date.strftime("%B %d")


        entries_by_day = sorted([(k, list(v)) for k, v in itertools.groupby(entries, day_func)], reverse= True)

        return dict(entries = entries_by_day, display_day = display_day, classify = classify, class_enumerate = class_enumerate)

    @expose(template="genshi:gibethemetechgeneral2008a.templates.archives")
    @add_plugin_data(template="genshi:gibethemetechgeneral2008a.templates.archives")
    def archives(self, blog, action, **kw):
        year = kw.get('year', None)
        if year is None:
            year = utcnow().year

        st = datetime(year = int(year), month = int(kw.get('month', 1)), day = int(kw.get('day', 1)))
        day = kw.get('day', None)
        month = kw.get('month', None)
        if day:
            et = st + timedelta(days=1)
        elif month:
            et = st + timedelta(days=32)
            et = datetime(et.year, month=et.month, day=1)
        else:
            et = st + timedelta(days=366)
            et = datetime(et.year, month=1, day=1)

        # posts = model.Post.select((model.Post.c.published == True) & (model.Post.c.creation_time.between(st, et)), order_by=model.desc(model.Post.c.creation_time))

        entries = model.session.query(ChannelEntry).filter(ChannelEntry.c.selected == True)
        if year:
            entries = entries.filter(ChannelEntry.c.published.between(st, et))
        entries = entries.order_by(model.desc(ChannelEntry.c.published))

        entries = list(entries)

        def day_func(e):
            return date(e.published.year, e.published.month, e.published.day)

        now = utcnow()

        def display_day(some_date):
            if some_date == now.date():
                return "Today"

            if some_date == now.date() - timedelta(days=1):
                return "Yesterday"

            return some_date.strftime("%B %d")


        entries_by_day = sorted([(k, list(v)) for k, v in itertools.groupby(entries, day_func)], reverse= True)

        return dict(entries = entries_by_day, display_day = display_day, classify = classify, class_enumerate = class_enumerate)

    @expose(template="genshi:gibethemetechgeneral2008a.templates.archives")
    @add_plugin_data(template="genshi:gibethemetechgeneral2008a.templates.archives")
    def tags(self, blog, action, tagname):
        limit = 0
        entries = model.session.query(ChannelEntry)
        entries = entries.filter(ChannelEntry.c.selected == True)
        entries = entries.filter(entries.join_via(['entry', 'tags']))
        entries = entries.filter(EntryTag.c.tag == tagname)
        entries = entries.order_by(model.desc(ChannelEntry.c.published))
        entries = entries.limit(limit)

        entries = list(entries)

        def day_func(e):
            return date(e.published.year, e.published.month, e.published.day)

        now = utcnow()

        def display_day(some_date):
            if some_date == now.date():
                return "Today"

            if some_date == now.date() - timedelta(days=1):
                return "Yesterday"

            return some_date.strftime("%B %d")


        entries_by_day = sorted([(k, list(v)) for k, v in itertools.groupby(entries, day_func)], reverse= True)

        return dict(entries = entries_by_day, display_day = display_day, classify = classify, class_enumerate = class_enumerate)
